#!/bin/bash

# Set Go version and download URL
GO_VERSION="1.24.3"
GO_URL="https://dl.google.com/go/go${GO_VERSION}.linux-amd64.tar.gz"
INSTALL_DIR="/usr/local"
PROFILE_DIR="/etc/profile.d"
GO_PROFILE="${PROFILE_DIR}/golang.sh"

# Check if running as root
if [ "$(id -u)" != "0" ]; then
    echo "Please run this script as root (use sudo)"
    exit 1
fi

# Check if aria2c is installed, install if not
if ! command -v aria2c >/dev/null 2>&1; then
    echo "aria2c not found, installing via apt..."
    apt update
    apt install -y aria2
    if [ $? -ne 0 ]; then
        echo "Failed to install aria2, check apt sources or network"
        exit 1
    fi
fi

# Download Go package
echo "Downloading Go ${GO_VERSION} using aria2c..."
aria2c -x 16 --allow-overwrite=true "${GO_URL}" -o go.tar.gz -d /tmp
if [ $? -ne 0 ]; then
    echo "Download failed, check network or URL"
    exit 1
fi

# Extract and install
echo "Installing Go to ${INSTALL_DIR}..."
tar -C "${INSTALL_DIR}" -xzf /tmp/go.tar.gz
if [ $? -ne 0 ]; then
    echo "Installation failed, check archive"
    exit 1
fi

# Clean up downloaded archive
rm -f /tmp/go.tar.gz

# Set environment variables
echo "Configuring environment variables..."
cat > "${GO_PROFILE}" << EOF
# Go environment variables
export PATH=\$PATH:${INSTALL_DIR}/go/bin
export GOROOT=${INSTALL_DIR}/go
export GOPATH=\$HOME/go
export PATH=\$PATH:\$GOPATH/bin
EOF

# Make profile script executable
chmod +x "${GO_PROFILE}"

# Load environment variables
source "${GO_PROFILE}"

# Verify installation
if command -v go >/dev/null 2>&1; then
    INSTALLED_VERSION=$(go version)
    echo "Go installed successfully: ${INSTALLED_VERSION}"
else
    echo "Go installation failed, check script"
    exit 1
fi

echo "Installation complete! "
